package com.example.javaffmpeg.controller;

import com.example.javaffmpeg.bean.Result;
import com.example.javaffmpeg.bean.Room;
import com.example.javaffmpeg.config.RoomsConfig;
import com.example.javaffmpeg.timer.MyTimer;
import com.github.jazzhow.command4j.CommandManager;
import com.github.jazzhow.command4j.CommandProcess;
import com.github.jazzhow.command4j.exceptions.ProcessExistException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;
@CrossOrigin
@RestController()
@RequestMapping("/video")
@Slf4j
@Component
public class VideoHandlerController {
    @Autowired
    private CommandManager commandManager;
    @Autowired
    private RoomsConfig roomsConfig;

    @GetMapping("/openFfmpeg")
    public Result openFfmpeg(String roomName) {
        String format = "ffmpeg -i rtsp://192.168.1.9:8555/test -c copy -f hls -hls_time 2.0 -hls_list_size 1 -hls_wrap 5 -s 216x384 -b:v 64k -y %s:/nginx/html/hls/%s";
        String rtspUrl = String.format(
                format, "e", "机房.m3u8"
        );
        try {
            commandManager.exec("111", rtspUrl);
        } catch (Exception e) {
            log.info(111 + "----------" + e.getMessage());
        }


        return new Result(0, "sucess");
    }


    //根据机房打开直播转码
    @GetMapping("/openFfmpegByRoom")
    public Result openFfmpegByRoom(String roomName) {
        log.info(roomName + "----------");
        Room room = roomsConfig.getMap().get(roomName);
        if (room == null) {
            return new Result(0, "没有查询到该机房的配置信息");
        }
        List<Map<String, String>> urllist = new ArrayList();
        for (int i = 0; i < room.getEquipmentUrl().size(); i++) {

            String rtsp = "ffmpeg -i rtsp://%s:%s@%s:%s%s";
            rtsp = String.format(
                    rtsp,
                    room.getAccount(),
                    room.getPass(),
                    room.getIp(),
                    room.getPort(),
                    room.getEquipmentUrl().get(i)
            );
            String format = rtsp + " -c copy -f hls -hls_time 2.0 -hls_list_size 1 -hls_wrap 15 -s 216x384 -b:v 64k -y %s:/nginx/html/hls/%s" + "";
            String channal = room.getName() + i + "video.m3u8";
            String rtspUrl = String.format(
                    format,
                    roomsConfig.getRootUrl(),
                    channal
            );

            try {
                commandManager.exec(channal, rtspUrl);
            } catch (Exception e) {
                log.info(channal + "----------" + e.getMessage());
            }
            String temUrl = "http://%s:%s/hls/" + channal;
            temUrl = String.format(temUrl, roomsConfig.getNginxIp(), roomsConfig.getNginxPort());
            Map<String, String> map = new HashMap<>();
            map.put("m3u8", temUrl);
            map.put("rtsp", rtsp);
            map.put("name", room.getEquipmentName().get(i));
            urllist.add(map);
        }
        MyTimer.processMap.put(roomName, LocalDateTime.now());
        return new Result(0, "sucess", urllist);
    }


    //根据机房打开直播转码
    @GetMapping("/openFfmpegByTime")
    public Result openFfmpegByTime(String rtsp,String endtime, String videoName, String userAccount) {
        log.info(rtsp + "先关闭失败----------" + rtsp);

        //判断该用户是否存在其他的操作 直接给关闭
        try {
            // 实行命令
            commandManager.destroy(userAccount);
        } catch (Exception e) {
            log.info(userAccount + "先关闭失败----------" + e.getMessage());
        }

        rtsp=rtsp+"&endtime="+endtime;
        Result reslut=  new Result(0, "sucess");
        String format = rtsp + " -c copy -f hls -hls_time 2.0 -hls_list_size 1 -hls_wrap 15 %s:/nginx/html/hls/%s" + "";
        String rtspUrl = String.format(
                format,
                roomsConfig.getRootUrl(),
                videoName+".m3u8"
        );
        String temUrl = "http://%s:%s/hls/" + videoName+".m3u8";
        temUrl = String.format(temUrl, roomsConfig.getNginxIp(), roomsConfig.getNginxPort());
        try {
            // 实行命令
            commandManager.exec(userAccount, rtspUrl);
            //保存 生成m3u8地址
            temUrl = String.format(temUrl, roomsConfig.getNginxIp(), roomsConfig.getNginxPort());
            reslut.setUrl(temUrl);
        } catch (Exception e) {
            reslut.setStatus(1);
            reslut.setMessage("查询失败");
            reslut.setUrl("");
        }
        return reslut;
    }


    @GetMapping("/closeAllChannel")
    public Result closeAllChannel() {
        try {
            commandManager.destroyAll();
        } catch (Exception e) {
            return new Result(1, "关闭失败: " + e.getMessage());
        }
        return new Result(0, "sucess");
    }

    @GetMapping("/queryAllChannel")
    public Result queryAllChannel() {
        String allProcessStr = "all: ";
        Collection<CommandProcess> allProcess = commandManager.getAllProcess();
        for (CommandProcess item : allProcess) {
            allProcessStr = allProcessStr + "--" + item.getProcessId();
        }
        return new Result(0, allProcessStr);
    }


}
